#!/usr/bin/env python                                         # THIS IS SERVER.PY

import socket                                                 # Import socket module
import select
import threading
import time

class receive_connections(threading.Thread):
    def __init__(self, listClients, maxUsers, names):
        threading.Thread.__init__(self)
        self.clients = listClients
        self.max = maxUsers
        self.names = names
    def run(self):
        s.listen(5)
        while len(self.clients) < self.max:
            print "clients: ", str(len(self.clients)), "max", str(self.max)
            c, addr = s.accept()                                   # Establish connection with client.
            self.clients.append(c)                                      # Append the new connection to the list
            names[str(c.getpeername())] = str(c.getpeername()[1])
            print 'Got connection from', str(c.getpeername())
            c.send('Connection successful.')
            for rest in clients:
                if rest != c:
                    rest.send("User " + str(c.getpeername()[1]) + " connected.")
       
       

port = int(raw_input('Specify port: '))                       # Reserve a port for your service.
max = int(raw_input('Specify maximum users: '))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         # Create a socket object
host = socket.gethostname()                                   # Get local machine name
#print 'Your ip is: ' + s.getpeername()                                        
s.bind((host, port))                                          # Bind to the port
print 'Hosting at ' + str(s.getsockname())

names = {}

clients = []                                                  # Make a list of clients
empty = []
                                                               # Now wait for client connection.
acceptThread = receive_connections(clients, max, names)
acceptThread.start()

while len(clients) < 1:
    time.sleep(.005)

    
    
#^^^that waits for everyone to join the session

while True:
    read_ready, write_ready, errors = select.select(clients, clients, empty, 5000)
    for readclient in read_ready:
       message = readclient.recv(4096)
       
       
       if message[:6] == "/nick ":
           oldnick = names[str(readclient.getpeername())]
           newnick = message[6:]
           for ID in names.keys():
               if names[ID] == newnick:
                   message = ''
                   readclient.send("User already exists named " + newnick)
                   print oldnick, "tried to change nickname to", newnick, "but user already exists with that name."
                   break
           else:
               message = oldnick + " changed their name to " + newnick + "."
               names[str(readclient.getpeername())] = newnick
       else:
           message = names[str(readclient.getpeername())] + ": " + message
       
       if message != '':
           print message
           for writeclient in write_ready:
               writeclient.send(message)
                   

       
